import { useEffect } from "react"
import { useSelector, useDispatch } from "react-redux"
import PropTypes from "prop-types"
import { message } from "antd"
import { loadJS } from "../../../utils/loadJS"
import {
  loadPreviewDepsAction,
  loadJQueryAction
} from "../../../store/actions/flowableAction"

const baseUrl = import.meta.env.VITE_FLOWABLE_URL

const ProcessPreview = ({
  modelId,
  versionId
}) => {

  const previewDepsLoaded = useSelector(state => state.flowable.previewDepsLoaded)
  const jQueryLoaded = useSelector(state => state.flowable.jQueryLoaded)

  const dispatch = useDispatch()

  useEffect(() => {
    if (!window.FLOWABLE) {
      window.FLOWABLE = {
        APP_URL: {}
      }
    } else {
      if (!window.FLOWABLE.APP_URL) {
        window.FLOWABLE.APP_URL = {}
      }
    }
    window.FLOWABLE.APP_URL.getModelHistoryModelJsonUrl = function (modelId, modelHistoryId) {
      return `/flowable-ui/modeler-app/rest/models/${modelId}/history/${modelHistoryId}/model-json`;
    }
    window.FLOWABLE.APP_URL.getModelModelJsonUrl = function (modelId) {
      return `/flowable-ui/modeler-app/rest/models/${modelId}/model-json`;
    }
  }, [])

  useEffect(() => {
    if (!previewDepsLoaded) {
      doLoadFlowableFiles()
    } else {
      doLoadModelJson()
    }
  }, [versionId])

  const doLoadModelJson = async () => {
    if (versionId) {
      document.querySelector('#J_preview').innerHTML = `<div
        id="bpmnModel"
        data-model-type="design"
        data-model-id=${modelId}
        data-history-id=${versionId}
      ></div>`
    } else {
      document.querySelector('#J_preview').innerHTML = `<div
        id="bpmnModel"
        data-model-type="design"
        data-model-id=${modelId}
      ></div>`
    }
    console.log(window.FLOWABLE.APP_URL.getModelHistoryModelJsonUrl)
    await loadJS(baseUrl + 'modeler/display/displaymodel.js', '#J_preview')
  }

  const doLoadFlowableFiles = async () => {
    try {
      if (!jQueryLoaded) {
        await dispatch(loadJQueryAction())
      }
      await dispatch(loadPreviewDepsAction())
      doLoadModelJson()
    } catch (error) {
      message.error(error.message || 'flowable静态文件加载失败')
    }
  }

  return <div id="J_preview"></div>
}

ProcessPreview.propTypes = {
  versionId: PropTypes.string,
  modelId: PropTypes.string
}

export default ProcessPreview